import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import processing.opengl.*;

private long timeLastUpdate;
private Level level;
private GameCamera gameCamera;
private Overlay overlay;
private Terrain terrain;

PFont font;

void setup ()
{
    size(800, 600, OPENGL);
    String[] gameDataFilePath = loadStrings("filepath.txt");
    //GameLoader gameLoader = new GameLoader();    
    //SceneNode scene = gameLoader.getScene(gameDataFilePath[0]);
    //level = new Level(scene);
    gameCamera = new GameCamera();
    gameCamera.setLocation(new PVector(0,10,0));
    overlay = new Overlay();
    terrain = new Terrain(gameCamera);
    timeLastUpdate = System.currentTimeMillis();
    
    font = createFont("Arial Bold",48);
}


void draw ()
{
  updateAll();
  drawAll();
}

void getInput()
{
  
}

void updateAll()
{
  long currentTime = System.currentTimeMillis();
  long timeElapsed = currentTime-timeLastUpdate;
  
  //level.update(timeElapsed);
  trackball();
  terrain.update();
}

void drawAll()
{
    background(50, 64, 42);
    lights();
    noStroke();
    fill(150, 195, 125);
    
    hint(ENABLE_DEPTH_TEST);
    gameCamera.apply();
    
    pushMatrix();
    terrain.draw();
    //level.draw();
    popMatrix();
    overlay.draw();
    
  textFont(font,36);
  fill(255);
  text(frameRate,20,60);
}

void trackball(){
  float xRotation = ((mouseX-width/2.0)/(width/2.0)*(PI/2))/50;
  float yRotation = -1*((mouseY-height/2.0)/(height/2.0)*(PI/2))/50;
//  System.out.println((mouseX-width/2.0) + " " + (mouseY-height/2.0) + "\n" + xRotation + " " + yRotation + "\n");
  
  gameCamera.shiftDirection(new PVector(xRotation, yRotation,0));
}

PVector getTrackballVector(){
  float mouseDownX =  (mouseX / (width/2f))-1;
  float mouseDownY = 1-(mouseY / (height/2f));
  float mouseDownZ = sqrt(max(1 - mouseDownX * mouseDownX - mouseDownY*mouseDownY,0));
  PVector mouseVector = new PVector(mouseDownX, mouseDownY, mouseDownZ);
  mouseVector.normalize();
  return mouseVector;
}

int signum(float f){
 if(f<0) return -1;
 else if(f>0) return 1;
 else return 0; 
}

void keyPressed ()
{      
      if (key == 'w') { 
        gameCamera.shiftLocationRelative(new PVector(0,0,1));
      } 
      else if (key == 's') { 
        gameCamera.shiftLocationRelative(new PVector(0,0,-1));
      } 
      if (key == 'a') { 
        gameCamera.shiftLocationRelative(new PVector(-1,0,0));
      } 
      else if (key == 'd') { 
        gameCamera.shiftLocationRelative(new PVector(1,0,0));
      } 
    
}

void mousePressed()
{
  println("bang");
}
